package persistence.sale;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import model.Sale;

public class SaleDAOPool implements SaleDAO {

    private static SaleDAOPool persistenceManager = null;
    private DataSource pool;
    private static final Logger logger = Logger.getLogger(SaleDAOJDBC.class.getName());

    private SaleDAOPool() {
    }

    public static SaleDAOPool getSaleDAOPoolImplementation() {
        if (persistenceManager == null) {
            persistenceManager = new SaleDAOPool();
        }
        return persistenceManager;
    }

    @Override
    public boolean setUp(String url, String driver, String user, String password) {
        Context env = null;
        try {
            env = (Context) new InitialContext().lookup("java:comp/env");
            pool = (DataSource) env.lookup("AppbuyPool");
            if (pool == null) {
                logger.log(Level.SEVERE, "No se encontro el DataSource");
                return false;
            }
        } catch (NamingException ex) {
            logger.log(Level.SEVERE, "No se pudo abrir la conexi�n contra base de datos", ex);
            return false;
        }
        return true;
    }

    @Override
    public boolean createSale(Sale sale) {
        SaleDAO jDBCSaleDAO = prepareForExecutingQuerry();
        if (jDBCSaleDAO == null) {
            return false;
        }
        boolean isExecutedOk = jDBCSaleDAO.createSale(sale);
        releaseQuerryResources(jDBCSaleDAO);
        return isExecutedOk;
    }

    @Override
    public void readAllSales(Map<String, Sale> saleArray) {
        SaleDAO jDBCSaleDAO = prepareForExecutingQuerry();
        if (jDBCSaleDAO == null) {
            return ;
        }
        jDBCSaleDAO.readAllSales(saleArray);
        releaseQuerryResources(jDBCSaleDAO);
    }

    @Override
    public boolean disconnect() {
        return true;
    }

    private SaleDAO prepareForExecutingQuerry() {
        SaleDAOJDBC jDBCpersistenceManager = new SaleDAOJDBC();
        Connection connection;
        try {
            connection = pool.getConnection();
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "No se pudo abrir la conexion contra la base de datos", ex);
            return null;
        }
        jDBCpersistenceManager.setConnection(connection);
        return jDBCpersistenceManager;
    }

    private void releaseQuerryResources(SaleDAO saleDAO) {
        saleDAO.disconnect();
    }
}
